<script lang="ts" setup>
import PageTable from '@/components/q-table/component/page-table.vue';
import { usePageTable, useUpset } from '@/hooks';
import { EditAppParams, IApp } from '@/service';
import { NButton } from 'naive-ui';

const tableRow = ref<IApp>();

const { dialog, message } = useFeedback(['dialog', 'message']);

const { pageTableRef, columns, operations, tableRequest, refreshTable, getTableInstance } = usePageTable<IApp>({
	api: api.app.getPaginationApp,
	columns: [
		{ field: 'appid', title: 'AppID', searchFormItem: { type: 'n-input' } },
		{ field: 'name', title: '应用名称', searchFormItem: { type: 'n-input' } },
		{ field: 'introduction', title: '应用简介' },
		{ field: 'description', title: '应用描述' },
	],
	operations: [
		{
			label: '编辑',
			key: 'edit',
		},
		{
			label: '删除',
			key: 'delete',
			type: 'error',
		},
	],
});

const { formItems, handleAdd, handleEdit } = useUpset<EditAppParams, string>({
	formItems: [
		{
			field: 'appid',
			title: 'AppID',
			type: 'n-input',
			validate: [{ required: true, message: '请输入AppID' }],
		},
		{
			field: 'name',
			title: '应用名称',
			type: 'n-input',
			validate: [{ required: true, message: '请输入应用名称' }],
		},
		{
			field: 'introduction',
			title: '应用简介',
			type: 'n-input',
			props: { type: 'textarea' },
		},
		{
			field: 'description',
			title: '应用描述',
			type: 'n-input',
			props: { type: 'textarea' },
		},
	],
	api: (data) => (tableRow.value ? api.app.updateApp({ _id: tableRow.value._id!, ...data }) : api.app.addApp(data)),
	success: () => {
		refreshTable();
	},
	title: '应用',
	modalOptions: {
		class: 'w-[500px]',
	},
});

const handleAddApp = () => {
	handleAdd({});
};

const handleEditApp = (row: IApp) => {
	tableRow.value = row;
	handleEdit({
		initialData: row,
	});
};

const handleDeleteApp = (row: IApp) => {
	const deleteDialog = dialog.warning({
		title: '删除应用',
		content: '确定删除该应用吗？',
		positiveText: '确定',
		negativeText: '取消',
		onPositiveClick: async () => {
			try {
				deleteDialog.loading = true;
				await api.app.deleteApp(row._id!);
				message.success('删除成功');
				getTableInstance()?.remove(row);
			} catch (error) {
				message.error('删除失败');
			} finally {
				deleteDialog.loading = false;
			}
		},
	});
};

const handleSelect = (params: { key: string; row: IApp }) => {
	switch (params.key) {
		case 'add':
			handleAddApp();
			break;
		case 'edit':
			handleEditApp(params.row);
			break;
		case 'delete':
			handleDeleteApp(params.row);
			break;
	}
};
</script>

<template>
	<page-wrap>
		<page-table ref="pageTableRef" :columns="columns" :operations="operations" :request="tableRequest" @operation-select="handleSelect">
			<template #toolbarButtons>
				<div class="space-x-2">
					<n-button type="primary" @click="handleAddApp">新增应用</n-button>
				</div>
			</template>
		</page-table>
	</page-wrap>
</template>
